package com.lanou3g.code0510;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/10;
 * Otherwise, I don't know who created it either
 */

@WebServlet(name = "CServlet", urlPatterns = "/c")
public class CServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得一个写字节流的输出流
        // 在同一个servlet中,字节流和字符流只能二选一
        OutputStream os = response.getOutputStream();

        Random random = new Random();
        if (random.nextBoolean()) {
            // 加载正常图片
            InputStream is = getServletContext()
                    .getResourceAsStream("pic/aa.png");
            // 读取输入流里的内容,生成一个byte数组
            byte[] bytes = IOUtils.toByteArray(is);
            os.write(bytes);// 写到输出流中
        } else {
            // 这个图片不允许访问,给错误图片看
            InputStream is = getServletContext()
                    .getResourceAsStream("pic/error.png");
            byte[] bytes = IOUtils.toByteArray(is);
            os.write(bytes);
        }


    }
}
